(function(){
	document.domain = "morningstar.com";	
	
	var top = this, QT_LOADER = {
		top: top,
		cfg: {
			release: '//quotespeed.morningstar.com/',
			staging: '//qsstage.morningstar.com/',
			pre:     '//qspre.morningstar.com/',
			dev:     '//rtqdev.morningstar.com/opt/'
		},
		parameters: {},
		version: 'dev',
		module: 'default',
		theme: 'default',
		client: 'default',
		tickerType: 'st',
		hasJQuery: false,
		jqueryList: ['lib/jquery.js'],
		//defautFileList : ['css/qs.css', 'css/ui/scrollbar.css', 'js/ui/util.js', 'js/ui/scrollpanel.js', 'js/com/qtcommon.js'],
		defautFileList: [],
		moduleMap: {
			'3.11': ['apis/quicktake/profile_stock.js'],//stock profile
			'3.1211': ['apis/quicktake/analysis-current.js'],//stock analysis current
			
			'3.1611':['apis/quicktake/insiders-overview.js'],
			'3.1612':['apis/quicktake/insiders-execcomp.js'],
			
			'3.22': ['apis/quicktake/industrypeer_stock.js'],//stock industry peer			
			'3.0111': ['apis/quicktake/dividends_stock.js'],//mlwm stock dividends
			'3.45':[]
		},
		themeMap: {
			'default': ['theme/quicktake/style.css'],
			'black': ['theme/quicktake/style.css'],
			'gray': ['theme/quicktake/style.css'],
			'custom': []
		},
		clientMap:{
			quest:['theme/default/style.css','apis/quicktake/quicktake_width.css','apis/quicktake/version_quest.js','apis/quicktake/set_width.js'],
			mlwm:['apis/quicktake/version_mlwm.js'],
			mssb:['apis/quicktake/version_quest.js'],
			qtrade:['apis/quicktake/version_qtrade.js'],
			spdr:['apis/quicktake/version_spdr.js'],
			disn:['theme/disn/style.css','theme/disn/style.js','apis/quicktake/quicktake_links.js']
		},
		themeTempList:['3.11', '3.26', '3.14','3.1411','3.1412', '3.15','3.1511','3.1512','3.1513','3.1514','3.1515','3.16','3.1611','3.1612','3.1613','3.1614','3.1615','3.1616','3.1617','3.1618','3.1619'],
		customStyleTempList:['3.11', '3.26', '3.14','3.1411','3.1412', '3.15','3.1511','3.1512','3.1513','3.1514','3.1515','3.16','3.1611','3.1612','3.1613','3.1614','3.1615','3.1616','3.1617','3.1618','3.1619','3.2511','3.2512','3.2513','3.2514','3.2515','3.2516','3.28','3.42'],
		styleTempListMap: {
			'3.11': 'profile',
			'3.26': 'operation',
			'3.14': 'valuation',
			'3.1411': 'valuation',
			'3.1412': 'wallStreetEst',
			'3.15': 'shareholders',
			'3.1511': 'shareholders overview',
			'3.1512': 'shareholders major',
			'3.1513': 'shareholders concentrated',
			'3.1514': 'shareholders buying',
			'3.1515': 'shareholders selling',
			'3.16': 'insiders',
			'3.1611': 'insiders overview',
			'3.1612': 'insiders exec',
			'3.1613': 'insiders activity',
			'3.1614': 'insiders key',
			'3.1615': 'insiders board',
			'3.1616': 'insiders comm',
			'3.1617': 'insiders itrans',
			'3.1618': 'insiders exec profile',
			'3.1619': 'insiders summary detail',
			//'3.2116': 'performance coupon info',
			'3.2511': 'portfolio style-allocation',
			'3.2512': 'portfolio sectors-stats',
			'3.2513': 'portfolio gics',
			'3.2514': 'portfolio holdings',
			'3.2515': 'portfolio regions',
			'3.2516': 'portfolio history',
			'3.28': 'performance',
			'3.42': 'quote'
		},		
		pageMapping:{
			'insider-summary.action':'3.1611',
			'executive-compensation.action':'3.1612',
			'insider-activity.action':'3.1613',			
			'key-executives.action':'3.1614',
			'board-of-directors.action':'3.1615',
			'insider-committees.action':'3.1616',
			'itrans.action':'3.1617',
			'executive-profile.action':'3.1618',
			'insider-summary-detail.action':'3.1619',
			'quote':'3.42'
		},
		initialize: function(){
			this.setParameters();
			
			//load file
			var list = this.defautFileList;
			if (!this.hasJQuery) {
				list = this.jqueryList.concat(list);
			}
			
//			for (var i = 0, l = this.themeTempList.length; i < l; i++) {
//				if(this.module)
//			}

			for (var i = 0, l = this.themeTempList.length; i < l; i++) {
				if(this.module == this.themeTempList[i]){
					list = list.concat(this.themeMap[this.theme]);
					break;
				}
			}
			
			

			//list = list.concat(this.themeMap[this.theme]);
			if (this.module != 'default' && typeof this.moduleMap[this.module]!='undefined' && this.client != 'disn') {
				list = list.concat(this.moduleMap[this.module]);
			}
			if (this.client != 'default' && typeof this.clientMap[this.client]!='undefined') {
				list = list.concat(this.clientMap[this.client]);
			}
			//load css before js
			list = list.sort(function(a, b){
				if (a.indexOf(".css") != -1 && b.indexOf(".js") != -1) {
					return -1;
				}
				else 
					if (a.indexOf(".js") != -1 && b.indexOf(".css") != -1) {
						return 1;
					}
					else {
						return 0;
					}
			});
			
			if(typeof(parent["QTLOADER_CONFIGTOOLKIT"])!= 'undefined'){
				var ConfigToolkit = parent["QTLOADER_CONFIGTOOLKIT"];
				var profile = ConfigToolkit.getConfig({
					client:this.client,
					theme:this.theme,
					module:this.module
				});
				if(profile.files.length){
					list = list.concat(profile.files);
				}
			}
			
			this.loadFileList(this.delRepeat(list));
			
			//add css className for black theme requirments

			for (var i = 0, l = this.themeTempList.length; i < l; i++) {
				if(this.module == this.themeTempList[i]){
					this.addThemeClass();
					break;
				}
			}
			
			//add css className for questrade requirments
			for (var i = 0, l = this.customStyleTempList.length; i < l; i++) {
				if(this.module == this.customStyleTempList[i]){
					this.addThemeClass();
					break;
				}
			}		
						
		},
		
		delRepeat : function(Array){
			var newArray = [];
			var provisionalTable = {};
			for (var i = 0, item; (item = Array[i]) != null; i++) {
				if (!provisionalTable[item]) {
					newArray.push(item);
					provisionalTable[item] = true;
				}
			}
			return newArray;
		},
		
		addThemeClass:function(){
			var self = this;
			if (window.attachEvent) {//IE
				window.attachEvent('onload', function(){
					self._addThemeClassToBody();
					//$('body').append('<style>html{overflow:auto !important;}body{overflow:auto;*overflow:hidden !important;}</style>');
				})
			}
			else {
				window.addEventListener('load', function(){
					self._addThemeClassToBody();
					//$('body').append('<style>html{overflow:auto !important;}body{overflow:auto;*overflow:hidden !important;}</style>');
				}, false)
			}
		},
		_addThemeClassToBody: function(){
			var module = this.styleTempListMap[this.module];
			var className = document.body.className || '';
			if(className.indexOf(module)<0){
				className += ('' == className ? "" : " ") + this.theme + " " + module + " " + this.tickerType.toLowerCase();
				document.body.className=className;
			}			
		},
		_getCookie:function(c_name){			
			var i, x, y=null, ARRcookies = document.cookie.split(";");
			for (i = 0; i < ARRcookies.length; i++) {
		        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
		        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
		        x = x.replace(/^\s+|\s+$/g, "");
				if (x == c_name) {
		            return unescape(y);
		        }
		    }
		},
		_setCookie:function(c_name,value,exdays){
			var exdate = new Date();
		    exdate.setDate(exdate.getDate() + exdays);
		    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
		    document.cookie = c_name + "=" + c_value;
		},
		setParameters: function(){
			var pageStrArr = window.location.pathname.split('/');
			var pageStr = pageStrArr[pageStrArr.length-1]
			var search = window.location.search;
			if (search.substr(1)) {
				var queryString = search.substr(1).split('&');
				for (var i = 0; i < queryString.length; i++) {
					var param = queryString[i].split("=");
					this.parameters[param[0]] = param[1];
				}
			}
			
			
			this.module = this.parameters["qs_qt_module"] || this.pageMapping[pageStr] || 'default';
			this.tickerType = this.parameters["tickerType"] || 'st';
			
			var versionStr = this.parameters["qt_version"] || '',//added by wind 20110803 to solve the parameter problem
				themeStr = this.parameters["theme"] || '', //added by wind 20110808 to solve the parameter problem
				clientStr = this.parameters["APIclientId"] || 'default';//added by wind 20110808 to solve the parameter problem
				
            
			
			if(this._getCookie('qs_api_version')&&versionStr==''){
                versionStr=this._getCookie('qs_api_version');
            }
            this._setCookie('qs_api_version',versionStr,1);
			if(this._getCookie('theme')&&themeStr==''){
                themeStr=this._getCookie('theme');
            }
            this._setCookie('theme',themeStr,1);
			if(this._getCookie('APIclientId')&&clientStr=='default'){
                clientStr=this._getCookie('APIclientId');
            }
			
			this.theme = themeStr;
			this.client = clientStr;
			this.version = versionStr;
			
			if (typeof(this.module) == 'undefined' || this.module == '' || this.module == 'default') {
				if(typeof(parent["QuicktakeDemo"])!='undefined'){//api
					var tabId = parent["QuicktakeDemo"].tabId;
					var subId = parent["QuicktakeDemo"].subTabId;
					this.module = subId || tabId;
				}else{//terminal
					if(typeof(parent["RTQ_Quicktake"])!="undefined"){
						var currentId = parent["RTQ_Quicktake"].currentId;
						if(typeof(currentId)!='undefined'){
							var qtObj = parent["QS"]["Data"].getQuickTake(currentId);
							var tabId = qtObj.tabId;
							var subId = qtObj.subTabId;
							this.module = subId || tabId;
						}
					}					
				}
			}
			
			if ((typeof(this.client) == 'undefined' || this.client == ''|| this.client == 'default')&&typeof(parent["instid"])!='undefined') {
				var client = parent["instid"].toLowerCase();
				this.client =client;
			}
			
			if ((typeof(this.version) == 'undefined' || this.version == '')&&typeof(parent["QS_VERSION"])!='undefined') {
				var version = parent["QS_VERSION"].toLowerCase();
				this.version =version;
			} 
			
			this._setCookie('APIclientId',clientStr,1);
			
			
			if (typeof($) != 'undefined') {
				this.hasJQuery = true;
			}
			
			if(this.version == "staging"){
				if (parent.location.href.indexOf("prestage/") > -1) {
					this.cfg["staging"] += "prestage/";
				}
			}
		},
		loadFileList: function(url){
			if (typeof(url) == 'string' && (url.replace(/(^\s*)|(\s*$)/g, "")) != '') {
				url = this.cfg[this.version] + url;
				this.loadFile(url);
			}
			else 
				if (typeof(url) == 'object' && typeof(url.length) != 'undefined' && url.length > 0) {
					for (var i = 0, l = url.length; i < l; i++) {
						this.loadFileList(url[i]);
					}
				}
		},
		loadFile: function(url){
			if (url.lastIndexOf('.js') == url.length - 3) {
				this.loadJS(url);
			}
			else 
				if (url.lastIndexOf('.css') == url.length - 4) {
					this.loadCSS(url);
				}
		},
		loadCSS: function(url){
			var fileRef = document.createElement("link");
			fileRef.setAttribute("rel", "stylesheet");
			fileRef.setAttribute("type", "text/css");
			fileRef.setAttribute("href", url);
			document.getElementsByTagName("head")[0].appendChild(fileRef);
		},
		loadJS: function(url){
			var fileRef = document.createElement('script');
			fileRef.setAttribute("type", "text/javascript");
			fileRef.setAttribute("src", url);
			document.getElementsByTagName("head")[0].appendChild(fileRef);
		}
	}
	top["QT_LOADER"] = QT_LOADER;
	QT_LOADER.initialize();

})();